<?php
namespace Modules\Activity\Entities;

use Modules\Activity\Entities\BaseActivityModel;
use Modules\Activity\Entities\Ticket;

use \Modules\Asset\Entities\Package;
use \Modules\Asset\Entities\PackageSku;

use ThrowException;
use DB;


// 此类活动类的分支， 此类活动仅限积分定价，并且参与时不会创建订单
class BaseActivityModelForNoOrder extends BaseActivityModel
{
    // 运行抽奖逻辑
    public function run($user, $total, $options = [])
    {
        DB::beginTransaction();

        $description = '参与活动扣除';
        Ticket::out($user, $this, $total, $description) ?: ThrowException::Conflict('剩余次数不足~', 14002);

        $skuMaps = $this->pickLuckySkus(1, $user, NULL, $options) ?: ThrowException::Conflict('奖品抽取失败~');

        if (!count($skuMaps)) {
            return false;
        }

        $package = Package::create([
            'title' => $this->title,
            'node_id' => $this->id,
            'node_type' => $this->activityType,
            'node_uuid' => $this->uuid,
            'node_money_price' => $this->money_price,
            'node_score_price' => $this->score_price,
            'activity_id' => NULL,
            'activity_type' =>  NULL,
            'activity_uuid' =>  NULL,
            'sku_total' => $total,
            'user_id' => $user->id,
            'status' =>  0,
            'pay_order_id' => NULL,
            'room_id' => NULL
        ]);

        $order = NULL;
        // 开盒取出奖品
        $package->createSkus($skuMaps, $order);
        $package->openBox();

        DB::commit();

        // 更新用户参与次数
        $this->updateJoinStat($user, [
            'total' => $total
        ]);

        return $package;
    }

    // 检查每个用户限制参与次数
    public function checkPerUserLimit($user, $total)
    {
        if (!$this->per_user_limit) {
            return true;
        }

        $completedTotal = ActivityOrder::paid()->where('node_type', $this->activity_type)->where('user_id', $user->id)->where('node_id', $this->id)->sum('sku_total');

        if ($completedTotal + $total > $this->per_user_limit) {
            $remainTime = $this->per_user_limit - $completedTotal;
            $remainTime = $remainTime < 0 ? 0 : $remainTime;

            ThrowException::Conflict('整个活动每人限制参与' . $this->per_user_limit . '次， 您当前仅剩余' . $remainTime . '次参与机会~');
        }
    }

    // 获取某用户在此活动的参数次数
    // $room 为特定房间
    public function getJoinTotal($user, $options = [])
    {
        $builder = ActivityOrder::paid()->where('node_type', $this->activity_type)->where('user_id', $user->id)->where('node_id', $this->id);

        // 限制特定的房间
        if ($options['room']) {
            $builder = $builder->where('room_id', $options['room']->id);
        }

        $completedTotal = $builder->sum('sku_total');

        return $completedTotal;
    }

}
